package com.example.shiwuyouproject.ui

import androidx.lifecycle.Observer
import androidx.lifecycle.observe
import com.blankj.utilcode.util.RegexUtils
import com.example.shiwuyouproject.base.BaseVmActivity
import com.example.shiwuyouproject.databinding.ActivityAccountbindingBinding
import com.example.shiwuyouproject.ui.modelview.AccountBindingViewModel
import com.example.shiwuyouproject.utils.CountDownTimerUtils
import com.yechaoa.yutilskt.ToastUtil
import com.yechaoa.yutilskt.YUtils

/**
 * 绑定账号
 */
class AccountBindingActivity :BaseVmActivity<ActivityAccountbindingBinding, AccountBindingViewModel>(){
    override fun viewModelClass(): Class<AccountBindingViewModel> = AccountBindingViewModel::class.java
    override fun getViewBinding(): ActivityAccountbindingBinding {
       return  ActivityAccountbindingBinding.inflate(layoutInflater)
    }
    private var mCountDownTimerUtils: CountDownTimerUtils? = null
    override fun initView() {
        mCountDownTimerUtils = CountDownTimerUtils(mBinding.tvCode, 60000, 1000)

    }
    private var bind_open_id=""
    private var bind_uniq_id=""
    override fun initData() {
        bind_open_id=intent.getStringExtra("bind_open_id").toString()
        bind_uniq_id=intent.getStringExtra("bind_uniq_id").toString()
    }
    override fun setListener() {
        mBinding.titleBar.tvBack.setOnClickListener { finish() }
        mBinding.tvCode.setOnClickListener {
            val username = mBinding.edPhone.text.toString().trim()
            if (username.isBlank()) {
                ToastUtil.show("手机号码不能为空！")
                return@setOnClickListener
            }
            if (!RegexUtils.isMobileSimple(username)) {
                ToastUtil.show("请输入正确手机号！")
                return@setOnClickListener
            }
            YUtils.showLoading(this, "获取中...")
            mViewModel.smsSend(username)

        }
        mBinding.btBanDing.setOnClickListener { //绑定
            if (mBinding.edPhone.text.length != 11) {
                ToastUtil.show("您输入的手机号位数不对！")
                return@setOnClickListener
            }
            if (mBinding.etUsername.text.isEmpty()) {
                ToastUtil.show("您输入验证码！")
                return@setOnClickListener
            }
            YUtils.showLoading(this, "绑定中...")
            mViewModel.userLogin(
                mBinding.edPhone.text.toString(),
                mBinding.etUsername.text.toString(),
                bind_open_id,
                bind_uniq_id
            )
        }
    }

    override fun observe() {
        mViewModel.myCodeState.observe(this, Observer<Boolean> {
            YUtils.hideLoading()
            if (it) {
                mCountDownTimerUtils?.start()
            }
        })

        mViewModel.userLoginState.observe(this, Observer<Boolean>{
            YUtils.hideLoading()
            ToastUtil.show("绑定成功！")
            setResult(1000)
            finish()
        })
    }
}